<template>
  <div class="app-container">
    <div
      style="padding: 2%;background: #ffffff;box-shadow: 0px 15px 24px 0px rgba(101,175,255,0.08);border-radius: 10px;"
    >
      <div style="display: flex;flex-direction: row;padding-bottom: 24px">
        <div style="flex: 1;display: flex;align-items: center">
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="handleCreate"
            v-bp="'/bs/sl_department/edit'"
          >
            {{$t("bs.add")}}
          </el-button>
          <el-button
            class="filter-item"
            plain
            size="small"
            style="margin-left: 10px;"
            type="primary"
            @click="expandAll"
          >
            全部展开
          </el-button>
          <el-button
              class="filter-item"
              plain
              size="small"
              style="margin-left: 10px;"
              type="primary"
              @click="collapseAll"
          >
            全部折叠
          </el-button>
        </div>
        <div style="flex: 1;display: flex;align-items: center;justify-content: flex-end">
          <el-popover
            v-model="tablesetvisible"
            placement="bottom-start"
            width="160"
          >
            <div class="setcheckbox">
              <el-checkbox v-model="checked" @change="checkall">全选/不选</el-checkbox>
              <el-checkbox v-for="(item,key) in fileds" :key="key" v-model="item.is_show" false-label="0" true-label="1">
                {{ item.title }}
              </el-checkbox>
            </div>
            <div slot="reference" class="hoverbutton">
              <img src="/static/table/fiter.png">
              <span style="margin-left: 8px;color: #666666">筛选</span>
            </div>
          </el-popover>
        </div>
      </div>
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        ref="mytable"
        row-key="id"
        style="width: 100%;"
        default-expand-all
        :tree-props="{children: 'children'}"
      >
        <el-table-column v-if="fileds.department_name.is_show==1" :label="$t('bs.departmentName')">
          <template slot-scope="{row}">
            {{ row.department_name }}
          </template>
        </el-table-column>
        <el-table-column v-if="fileds.department_type.is_show==1" :label="$t('bs.departmentType')">
          <template slot-scope="{row}">
            {{ row.department_type }}
          </template>
        </el-table-column>

        <el-table-column v-if="fileds.department_head.is_show==1" :label="$t('bs.departmentHead')">
          <template slot-scope="{row}">
            {{ row.department_head }}
          </template>
        </el-table-column>
        <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="{row,$index}">
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom-start">
              <el-button  v-bp="'/bs/sl_department/view'" circle icon="el-icon-edit" size="small" @click="handleUpdate(row)" />

            </el-tooltip>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="handleDelete([row.id])"
            >
              <el-tooltip slot="reference" class="item" effect="dark" content="删除" placement="bottom-start">
                <el-button
                  v-bp="'/bs/sl_department/edit'"
                  circle
                  icon="el-icon-delete"
                  size="small"
                  style="margin-left: 8px"
                />
              </el-tooltip>
            </el-popconfirm>
            <el-tooltip class="item" effect="dark" content="复制" placement="bottom-start">
              <el-button  v-bp="'/bs/sl_department/edit'" style="margin-left: 8px" circle icon="el-icon-magic-stick" size="small" @click="handleCopy(row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page_no"
        :total="total"
        @pagination="getList"
      />

    </div>
    <el-dialog :close-on-press-escape="false" :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="120px" style="padding-right:32px">
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item :label="$t('bs.parentDepartment')" prop="parent_id">

              <cy-tree-select
                v-model="temp.parent_id"
                :data="routesList"
                :props="{label:'department_name',children:'children'}"
                default-expand-all
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('bs.departmentName')" prop="department_name">
              <el-input v-model="temp.department_name" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.departmentType')" prop="department_type">
              <el-select v-model="temp.department_type">
                <el-option
                  v-for="(item,key) in department_type"
                  :key="key"
                  :label="item.dict_value"
                  :value="item.dict_key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="temp.department_type=='产线'" :span="24">
            <el-form-item label="导入时间" prop="import_time">
              <el-date-picker v-model="temp.import_time" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="请选择导入时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="temp.department_type=='产线'" label="产线号" prop="line_no">
              <el-input v-model="temp.line_no" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="temp.department_type=='产线'" label="导入位置" prop="import_position">
              <el-input v-model="temp.import_position" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="$t('bs.departmentHead')" prop="department_head">
              <el-input v-model="temp.department_head" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('bs.sort')" prop="px">
              <el-input v-model="temp.px" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary"  v-bp="'/bs/sl_department/edit'" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchTree, createData, updateData, delData, fetchDict } from '@/api/common'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import CyTreeSelect from '@/components/CyTreeSelect'
import { getMenu } from '@/api/user'
import { getStationAttrInfo, getStationGyxf } from '@/api/station' // secondary package based on el-pagination

export default {
  name: 'SlDepartment',
  components: { CyTreeSelect, Pagination },
  directives: { waves },
  data() {
    return {
      isExpand:true,
      checked: true,
      tablesetvisible: false,
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page_no: 1,
        limit: 20,
        sort: 'id desc',
        where: {}
      },
      showReviewer: false,
      temp: {
        // id: "",
        parent_id: '',
        department_type: '',
        department_name: '',
        department_head: '',
        import_time: '',
        import_position: '',
        line_no: '',
        px:50,
        // del_flag: "",
        // add_user_id: "",
        // add_time: "",
      },
      fileds: {
        parent_id: { filed: 'parent_id', title: '上级部门', is_show: '1' },
        department_name: { filed: 'department_name', title: '部门名称', is_show: '1' },
        department_type: { filed: 'department_head', title: '部门类型', is_show: '1' },
        department_head: { filed: 'department_head', title: '负责人', is_show: '1' }
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
       update: this.$t("bs.edit"),
        create: this.$t("bs.add")
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        parent_id: [{ required: true, message: '上级部门不能为空', trigger: 'change' }],
        department_name: [{ required: true, message: '部门名称不能为空', trigger: 'change' }],
        department_type: [{ required: true, message: '此项不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      routesList: [],
      department_type: []
    }
  },
  created() {
    this.getList()
    this.getDepartment()
  },
  methods: {
    async handleCopy(row) {
      this.temp = Object.assign({}, row) // copy obj
      //
      this.dialogStatus = 'create'
      this.temp.id = ''
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    async getDepartment() {
      const res = await fetchTree(null, '/api/auth/getdeptlist')
      // this.serviceRoutes = res.data
      // const routes = this.generateRoutes(res.data)
      if (!res.data) {
        res.data = []
      }
      res.data.unshift({
        href: '',
        id: '0',
        department_name: '顶级部门'
      })
      this.routesList = res.data
      const department = await fetchDict('department_type')
      this.department_type = department.data.items
    },
    checkall(val) {
      let check = '1'
      if (!val) {
        check = '0'
      }
      const keys = Object.keys(this.fileds)
      keys.map((item) => {
        this.fileds[item].is_show = check
      })
    },
    getList() {
      this.listLoading = true
      fetchTree(this.listQuery, '/api/auth/getdeptlist').then(response => {
        if (response.data) {
          this.list = response.data
          // this.total = response.data.count
        }
        this.listLoading = false
      })
    },
    handleFilter() {
      const ext_keys = ['limit', 'where', 'page_no', 'sort']
      this.listQuery.page_no = 1
      const queryParma = {}
      const listkeys = Object.keys(this.listQuery)
      for (const i in listkeys) {
        if (ext_keys.indexOf(listkeys[i]) == -1 && this.listQuery[listkeys[i]]) {
          queryParma['and'] = [
            { field: listkeys[i], operator: 'like', value: '%' + this.listQuery[listkeys[i]] + '%' }
          ]
        }
      }
      this.listQuery['where'] = queryParma
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: '',
        parent_id: '',
        department_type: '',
        department_name: '',
        department_head: '',
        import_time: '',
        import_position: '',
        line_no: '',
        px:50
        // del_flag: "",
        // add_user_id: "",
        // add_time: "",
      }
    },
    expandAll(){
      this.isExpand=true;
      this.$nextTick(() => {
        this.forArr(this.list, this.isExpand)
      })
    },
    collapseAll(){
      this.isExpand=false;
      this.$nextTick(() => {
        this.forArr(this.list, this.isExpand)
      })
    },
    forArr(arr, isExpand) {
      arr.forEach(i => {
        // toggleRowExpansion见element文档
        this.$refs.mytable.toggleRowExpansion(i, isExpand)
        if (i.children) {
          this.forArr(i.children, isExpand)
        }
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'department',
            add: this.temp
          }

          createData({ data: [data] }, 'sl_department').then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getDepartment()
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      //
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = {
            modelname: 'department',
            update: this.temp
          }
          createData({ data: [data] }, 'sl_department').then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getDepartment()
            this.getList()
          })
        }
      })
    },
    handleDeleteAll() {
      if (this.multipleSelection.length == 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      this.$confirm('你确定删除这' + this.multipleSelection.length + '条数据么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.handleDelete(this.multipleSelection.map(item=>item.id))
      })
    },
    handleDelete(ids) {
      delData({ id: ids.join(',') }, 'sl_department').then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.getList()
      })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style scoped="scoped" type="scss">
.pagination-container {
  padding: 0px;
  padding-bottom: 16px;
}

.hoverbutton {
  width: 70px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  border-radius: 3px;
}

.hoverbutton:hover {
  border: 1px solid #999999;
}

.setcheckbox .el-checkbox {
  margin-bottom: 10px;
}

.searchform .el-form-item {
  margin-bottom: 0px;
  min-width: 280px;
}
.el-table .cell{
  padding-right: 0px !important;
}
</style>

